from django import http
from django.views import View

from apps.areas.models import Area
from django.core.cache import cache

from utils.response_code import RETCODE


class AreasView(View):
    def get(self, request):
        # 1.获取parent_id
        parent_id = request.GET.get('area_id')
        # 2.判断parent_id 是否为None
        if parent_id is None:
            pro_list = cache.get('pro')

            if pro_list is None:

                # 3.为None则表示获取省的信息
                proviences = Area.objects.filter(parent__isnull=True)
                # 将对象列表转换为字典列表
                pro_list = []
                for pro in proviences:
                    pro_list.append({
                        'id': pro.id,
                        'name': pro.name
                    })

                # 设置缓存数据
                # cache.set(key,valule,second)
                cache.set('pro', pro_list, 24 * 3600)
            # 3.为None则表示获取省的信息
            proviences = Area.objects.filter(parent__isnull=True)
            # 将对象列表转换为字典列表
            pro_list = []
            for pro in proviences:
                pro_list.append({
                    'id': pro.id,
                    'name': pro.name
                })

            return http.JsonResponse({'code': RETCODE.OK, 'province_list': pro_list})

        else:
            # 4.不为None则表示获取市,区县的信息

            districts = Area.objects.filter(parent_id=parent_id)

            #

            # 对象列表转换为字典列表
            dis_list = []
            for item in districts:
                dis_list.append({
                    'id': item.id,
                    'name': item.name
                })

            return http.JsonResponse({'code': RETCODE.OK, 'subs': dis_list})
